//Created by Timothy Cheung

Ext.define('MajorProjectSenchaTouch.controller.DetailsView', {
    extend: 'Ext.app.Controller',
    config:{
        views: ['SearchModule.ResultList', 'DetailsViewModule.DetailsView', 'BookMarkedModule.BookMarkedDataview', 'MajorProjectSenchaTouch.view.SearchModule.DisplayResult', 'ExamPaperModule.ExamResultList', 'ExamPaperModule.DisplayExamResult'],
        refs:{
            detailsBtn: 'button[action = detailsTab]',
            availBtn: 'button[action = availTab]',
            resultListPage: 'resultpage',
            dv: 'detailsview',
            dvp: 'detailsViewPanel',
            bmDataview: 'BookMarkedDV',
            navView: 'mainNavView',
            detailsview: 'detailsview',
            availTab: 'availTab',
            searchView: 'searchView',
            searchpage: 'searchpage',
            // Added by Sean
			examResultListPage: 'examresultpage',
			examSearchView: 'searchExamView',
			examSearchPage: 'searchexampage',
			
            disclosureRecord: null
        },
        control:{
            detailsBtn:{
                tap: 'detailsTab'
            },
            availBtn:{
                tap: 'availTab'
            },
            resultpage:{
                itemtap: 'loadDetailsMain'
            },
			searchexampage:{
				itemtap: 'loadExamDetailsMain'
			},
            BookMarkedDV:{
                itemtap: 'loadBMDetailsMain'
            }
        }
    },
    
    /*
    |-------------------------------------------------------------------------------------------------
    | loadDetailsMain (@author : Timothy Cheung )
    |-------------------------------------------------------------------------------------------------
    |   Access point: Search Results Page itemtap event
    |   This function is triggered when the user taps on a result entry on the results list page. 
    |   The item details XML from the X-services API is parsed and loaded into the DetailsMains store,
    |   as well as added to the DetailsMainsTemp store. The DetailsView view is then pushed into the
    |   navigation view.
    */
    loadDetailsMain: function(list, index, item){
        var ctrl = this;
        //set loading mask to previous view
        var previousPage = ctrl.showMask();
        //create delayed task
        var task = Ext.create('Ext.util.DelayedTask', function(){
                 
            //set references to DetailsMains and DetailsMainsTemp stores
            var storeMain = Ext.getStore('DetailsMains');
            var storeTemp = Ext.getStore('DetailsMainsTemp');
            
            //retrieve set number(set_no) of the current search from the ResultsInfo store
            var set_no = Ext.getStore('ResultsInfo').getAt(0).data.setnumber;
            
            //retrieve record of entry tapped, extract set entry(set_entry)
            //and document number(docnum) value from record
            var record = item.getRecord();
            var set_entry = record.get('setentry');
            var docnum = record.get('docnum');
            
            //check if the current record exists in the DetailsMainsTemp store
            //if same record does not exist
            if(storeTemp.findRecord('docnum', docnum)==null){
                
                //load/reload DetailsMains store
                storeMain.load({
                    //set url for X-services API access
                    url: MajorProjectSenchaTouch.app.serverUrl + 'details/getDetails/' + set_no + '/' + set_entry,
                    
                    //d0 after load completed
                    callback: function(){
                        //if the number of records in DetailsMainsTemp store exceeds the record item limit (default: 10)
                        //*Note: tempStoreLimit value can be changed in app.js
                        if(storeTemp.getCount() >= MajorProjectSenchaTouch.app.tempStoreLimit)
                        {
                            //remove the first record added to DetailsMainsTemp store (FIFO)
                            storeTemp.removeAt(0);
                        }
                        //add loaded record into DetailsMainsTemp store
                        storeTemp.add(storeMain.getAt(0));
                        //hide loading mask set to the previous view
                        ctrl.hideMask(previousPage);
                    }
                });
            }
            //if same record exists
            else{
                //empty DetailsMains, retrieve record from DetailsMainsTemp and set as DetailsMains' active record
                storeMain.removeAll();
                storeMain.add(storeTemp.findRecord('docnum', docnum));
                //hide loading mask set to the previous view
                ctrl.hideMask(previousPage);
            }
            ctrl.disclosure = item.getRecord();
            //push DetailsView view into navigation view
            ctrl.pushView('Details View', 'detailsview');
        });
        //delay task for 1ms to resolve asynchronous issue with loading mask and store loading
        task.delay(1);
    },
	
	loadExamDetailsMain: function(list, index, item){
        var ctrl = this;
        //set loading mask to previous view
        var previousPage = ctrl.showMask();
        //create delayed task
        var task = Ext.create('Ext.util.DelayedTask', function(){
                 
            //set references to DetailsMains and DetailsMainsTemp stores
            var storeMain = Ext.getStore('DetailsMains');
            var storeTemp = Ext.getStore('DetailsMainsTemp');
            
            //retrieve set number(set_no) of the current search from the ResultsInfo store
            var set_no = Ext.getStore('ResultsInfo').getAt(0).data.setnumber;
            
            //retrieve record of entry tapped, extract set entry(set_entry)
            //and document number(docnum) value from record
            var record = item.getRecord();
            var set_entry = record.get('setentry');
            var docnum = record.get('docnum');
            
            //check if the current record exists in the DetailsMainsTemp store
            //if same record does not exist
            if(storeTemp.findRecord('docnum', docnum)==null){
                
                //load/reload DetailsMains store
                storeMain.load({
                    //set url for X-services API access
                    url: MajorProjectSenchaTouch.app.serverUrl + 'details/getDetails/' + set_no + '/' + set_entry,
                    
                    //d0 after load completed
                    callback: function(){
                        //if the number of records in DetailsMainsTemp store exceeds the record item limit (default: 10)
                        //*Note: tempStoreLimit value can be changed in app.js
                        if(storeTemp.getCount() >= MajorProjectSenchaTouch.app.tempStoreLimit)
                        {
                            //remove the first record added to DetailsMainsTemp store (FIFO)
                            storeTemp.removeAt(0);
                        }
                        //add loaded record into DetailsMainsTemp store
                        storeTemp.add(storeMain.getAt(0));
                        //hide loading mask set to the previous view
                        ctrl.hideMask(previousPage);
                    }
                });
            }
            //if same record exists
            else{
                //empty DetailsMains, retrieve record from DetailsMainsTemp and set as DetailsMains' active record
                storeMain.removeAll();
                storeMain.add(storeTemp.findRecord('docnum', docnum));
                //hide loading mask set to the previous view
                ctrl.hideMask(previousPage);
            }
            ctrl.disclosure = item.getRecord();
            //push DetailsView view into navigation view
            ctrl.pushView('Details View', 'detailsview');
        });
        //delay task for 1ms to resolve asynchronous issue with loading mask and store loading
        task.delay(1);
    },
	
    /*
    |-------------------------------------------------------------------------------------------------
    | loadBMDetailsMain (@author : Timothy Cheung )
    |-------------------------------------------------------------------------------------------------
    |   Access point: Book-Marked! items list itemtap event
    |   This function is triggered when the user taps on a Book-Marked! entry on the items list page. 
    |   The entry's attached record is retrieved and added to DetailsMains store. The DetailsView view is
    |   then pushed into the navigation view.
    */
    loadBMDetailsMain: function(list, index, item){
        
        var ctrl = this;
        //set loading mask to previous view
        var previousPage = ctrl.showMask();
        //create delayed task
        var task = Ext.create('Ext.util.DelayedTask', function()
        {
            //set reference to DetailsMains store
            var storeMain = Ext.getStore('DetailsMains');
            //retrieve entry item's attached record
            var record = item.getRecord();
            //remove previously loaded item (if any) from DetailsMains
            storeMain.removeAll();
            //add record into DetailsMains
            storeMain.add(record);
            ctrl.disclosure = item.getRecord();
            
            //push DetailsView view into navigation view
            ctrl.pushView('Details View', 'detailsview');
            //hide loading mask set to the previous view
            ctrl.hideMask(previousPage);
        
        });
        //delay task for 1ms to resolve asynchronous issue with loading mask and store loading
        task.delay(1);
    },
    /*
|--------------------------------------------------------------------------
| detailsTab (@author : Justina Lee)
|--------------------------------------------------------------------------
|
| Set mainTab as the active item of the details view panel. 
|
*/
    detailsTab: function(){                
        var view = this.getNavView();
        var current = view._activeItem;
        var currentDvp = current._items.items[1];
        
        currentDvp.animateActiveItem(0, this.slideRightTransition);
    },
    /*
|--------------------------------------------------------------------------
| availTab (@author : Timothy Cheung )
|--------------------------------------------------------------------------
| Access point: Tap event on Availability half of segmented button
| This function is triggered when the user taps on the Availability segmented button on
| the DetailsView view. The availTab is set as the active item of the Details View panel.
*/
    availTab: function(){
        var view = this.getNavView();
        //set reference to the active item of the current view inside navigation view
        var current = view._activeItem;
        //set reference to the current active instance of details view panel
        var currentDvp = current._items.items[1];
        
        //set reference to DetailsAvails and DetailsMains stores
        var storeAvails = Ext.getStore('DetailsAvails');
        var storeMains = Ext.getStore('DetailsMains');
        //retrieve document number from record in DetailsMains store
        var docnum = storeMains.getAt(0).data.docnum;
        
        //Load DetailsAvails store via availStatus function in availability.php
        storeAvails.load({
            url: MajorProjectSenchaTouch.app.serverUrl + 'availability/availStatus/' + docnum
        });
        
        //set AvailTab to be the active item of the currently active instance of details view panel
        currentDvp.animateActiveItem(1, this.slideLeftTransition);
    },
    //Transition settings
    slideLeftTransition: {
        type: 'slide', 
        direction: 'left'
    },
    slideRightTransition: {
        type: 'slide', 
        direction: 'right'
    },
    /*
|---------------------------------------------------------------------------------------------
| getDetails (@author : Timothy Cheung )
|---------------------------------------------------------------------------------------------
| Access point: Tapping on the add Book-Marked icons
| This function is triggered when the user taps on the add Book-Marked icons. 
| The X-services API is accessed and the returned XML is parsed returning a record
| which is loaded into the DetailsMains store. This record is then added to Book-Marked's
| local storage.
*/
    getDetails: function(list, index, item){
        
        var storeMain = Ext.getStore('DetailsMains');
        var set_no = Ext.getStore('ResultsInfo').getAt(0).data.setnumber;
        var record = item.getRecord();
        var set_entry = record.get('setentry');
       
        storeMain.load({
            url: MajorProjectSenchaTouch.app.serverUrl + 'details/getDetails/' + set_no + '/' + set_entry,
            
            callback: function(){                  
                var details =  storeMain.getAt(0);
                  
                /* After the store is loaded, call the addBookMark function in 
                   * BookMarked controller (@author: Justina lee)*/
                var bmCtrl = MajorProjectSenchaTouch.app.getController('BookMarked');
                bmCtrl.addBookMark(record, details);
            }
        });
    },
   /* 
|---------------------------------------------------------------------------------------------
| getAvail (@author : Timothy Cheung )
|---------------------------------------------------------------------------------------------
| Access point: Tapping on the shelf locator button or icons
| This function is triggered when the user taps on the shelf locator icons. 
| The X-services API is accessed and the returned XML is parsed returning a record
| which is loaded into the DetailsAvails store. This record is then accessed for manipulation by
| the ShelfLocator controller's processLocationData function.   
*/
    getAvail: function(list, index, item, button){
        var store = Ext.getStore('DetailsAvails');
        var record = item.getRecord();
        var docnum = record.get('docnum');

        store.load({
            url: MajorProjectSenchaTouch.app.serverUrl + 'availability/availStatus/' + docnum,

            /* After the store is loaded, retrieves collection and shelfnumber data
             * and passes them to ShelfLocator controller for processing (@author: Lim Yi Le)*/
            callback: function(){
                var availDetails = store.getAt(0);
                var collection = availDetails.data.collection;
                var shelfnumber = availDetails.data.location;
                var fpControl = MajorProjectSenchaTouch.app.getController('ShelfLocator');
                fpControl.processLocationData(collection, shelfnumber);
            }
        });
    },
    //Utility function to set title and push view into navigation view
    pushView: function(setTitle, setXtype){
        var view = this.getNavView();
        
        view.push({
            title: setTitle,
            xtype: setXtype
        })
    },
    //Utility function to show loading mask
    showMask: function(){
        var view = this.getNavView();
        var previousPage = view._activeItem;

        previousPage.setMasked({
            xtype: 'loadmask',
            message: 'Please wait...'
        });

        return previousPage;
    },
    //Utility function to hide loading mask
    hideMask: function(previousPage){
        previousPage.setMasked(false);
    }
});
